package com.shitou.shitouproduct.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shitou.shitoucommons.utils.AllSaltEnum;
import com.shitou.shitouproduct.entity.CarouselEntity;
import com.shitou.shitouproduct.entity.HotSpuEntity;
import com.shitou.shitouproduct.entity.SpuImagesEntity;
import com.shitou.shitouproduct.entity.SpuInfoEntity;
import com.shitou.shitouproduct.service.CarouselService;
import com.shitou.shitouproduct.service.HotSpuService;
import com.shitou.shitouproduct.service.SpuImagesService;
import com.shitou.shitouproduct.service.SpuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
@Slf4j
@Component
public class MyTask implements InitializingBean {

    @Resource(name = "RedisTemplate")
    private RedisTemplate redisTemplate;
    @Resource
    private HotSpuService hotSpuService;
    @Resource
    private CarouselService carouselService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private SpuInfoService spuInfoService;


    /**
     * 每一个小时执行一次,,对redis中的所有商品进行排序计数
     *
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void execute() {
        // 执行具体的定时任务逻辑
        Map<String, Integer> spuCountMap = JSON.parseObject((String) redisTemplate.opsForValue().get("spuCount"), Map.class);

        if ( spuCountMap == null ){
            spuCountMap = new HashMap<String, Integer>();
        }else {

            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(spuCountMap.entrySet());
            // 自定义Comparator接口实现倒序排列
            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue());
                }
            });
            List<CarouselEntity> carouselEntities = new ArrayList<>();
            List<HotSpuEntity> hotSpuEntities = new ArrayList<>();
            CarouselEntity carousel = null;
            HotSpuEntity hotSpu = null;
            int index = -1 ;
            Date date = new Date();
            // 取前面6个或者小于6个
            for (Map.Entry<String, Integer> entry : list) {
                // 判断该商品是否被售卖
                String productToken = String.valueOf(new Sha256Hash(entry.getKey(), AllSaltEnum.SALT.getSalt()));
                Integer saleCount = (Integer) redisTemplate.opsForValue().get("saleCount:" + productToken);
                if ( saleCount == null || saleCount > 0){
                    continue;
                }
                if ( index == 5 ){
                    break;
                }
                carousel = new CarouselEntity();
                carousel.setSpuId(Long.valueOf(entry.getKey()));
                carousel.setCreateTime(date);
                carousel.setStatus(1);
                carousel.setUpdateTime(date);
                SpuImagesEntity spuImagesEntity = spuImagesService.getOne(new QueryWrapper<SpuImagesEntity>()
                        .eq("spu_id", Long.valueOf(entry.getKey())));
                SpuInfoEntity spuInfo = spuInfoService.getOne(new QueryWrapper<SpuInfoEntity>()
                        .eq("id", Long.valueOf(entry.getKey())));
                if ( spuImagesEntity != null ){
                    carousel.setSpuImage(spuImagesEntity.getImgUrl());
                }
                hotSpu = new HotSpuEntity();
                if ( spuInfo != null ){
                    hotSpu.setSpuId(Long.valueOf(entry.getKey()));
                    hotSpu.setSpuTitle(spuInfo.getSpuName());
                    hotSpu.setSpuDetail(spuInfo.getSpuDescription());
                }
                hotSpu.setStatus(1);
                hotSpu.setCreateTime(date);
                hotSpu.setUpdateTime(date);

                hotSpuEntities.add(hotSpu);
                carouselEntities.add(carousel);
                index ++;
            }

            // 将之前的展示的商品设置未不可用
            deleteOrderProduct(carouselEntities, hotSpuEntities);
//            System.out.println(carouselEntities);
            // 开始插入
            carouselService.saveOrUpdateBatch(carouselEntities);
            hotSpuService.saveOrUpdateBatch(hotSpuEntities);
        }

    }


    /**
     * 将之前的展示的商品设置未不可用,,,并追加至6个。。。懒得做了，giao
     * @param carouselEntities
     * @param hotSpuEntities
     */
    public void deleteOrderProduct(List<CarouselEntity> carouselEntities, List<HotSpuEntity> hotSpuEntities){

        if ( carouselEntities.size() <= 6 ){


        }
        List<CarouselEntity> tempCarouseList = carouselService.list(new QueryWrapper<CarouselEntity>()
                .eq("status", 1));
//        int appendSize = 6 - carouselEntities.size();

        // TODO 查看是否由相同的商品

        // TODO 查看数据库中的商品是否已经售卖了

        // TODO 对原有数据进行排序,,取最大的

        // TODO 直接将数据库中的设置未0
        if ( tempCarouseList .size() > 0 ){
            Iterator<CarouselEntity> iterator = tempCarouseList.iterator();
            while (iterator.hasNext()) {
                CarouselEntity next = iterator.next();
                next.setStatus(0);
            }
            carouselService.updateBatchById(tempCarouseList);
        }

        if ( hotSpuEntities.size() < 6 ){


        }
        List<HotSpuEntity> tempHotSpuList = hotSpuService.list(new QueryWrapper<HotSpuEntity>()
                .eq("status", 1));
//        int appendSize = 6 - hotSpuEntities.size();

        // TODO 查看是否由相同的商品

        // TODO 查看数据库中的商品是否已经售卖了

        // TODO 对原有数据进行排序,,取最大的

        // TODO 直接将数据库中的设置未0
        if ( tempHotSpuList.size() > 0 ){
            Iterator<HotSpuEntity> iterator = tempHotSpuList.iterator();
            while (iterator.hasNext()) {
                HotSpuEntity next = iterator.next();
                next.setStatus(0);
            }
            hotSpuService.updateBatchById(tempHotSpuList);
        }
    }


    /**
     * 每天零点清除搜索记录
     */
    @Scheduled(cron = "0 0/4 * * * ?")
    public void task() {
        // 定时任务逻辑
        Map<String, Integer> spuCountMap = JSON.parseObject((String) redisTemplate.opsForValue().get("spuCount"), Map.class);
        if ( spuCountMap == null ){
            spuCountMap = new HashMap<String, Integer>();
        }else {
            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(spuCountMap.entrySet());

            Iterator<Map.Entry<String, Integer>> iterator = list.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Integer> entry = iterator.next();
                String key = entry.getKey();
                //根据业务逻辑修改value
                entry.setValue(0);
            }
            redisTemplate.opsForValue().set("spuCount", JSON.toJSONString(spuCountMap));
        }
    }

    /**
     * 创建Bean时调用,,,启动定时任务
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("启动了轮播图和热点商品切换~定时任务");
    }
}
